<template>
  <div class="login-container">
    <div class="left-section">
      <h2 class="platform-title">AutoElectrodePlatformV2</h2>
      <div class="lab-scene">
        <!-- 这里可以使用图片或者更复杂的 SVG、3D 组件来展示实验室场景 -->
        <img src="@/assets/images/lab_scene.png" alt="Lab Scene" class="lab-image" />
      </div>
    </div>
    <div class="right-section">
      <div class="form-content">
        <h3>账号登录</h3>
        <div class="line_cl">
          <div class="left_cl"></div>
          <div class="right_cl"></div>
        </div>
        <el-form ref="formRef" :model="loginForm" :rules="rules" @submit.prevent="commEvent.onLogin">
          <el-form-item prop="account">
            <el-input
              v-model="loginForm.account"
              placeholder="请输入您的账号"
              class="item-field"
              @keyup.enter="commEvent.onLogin"
            >
              <template #prefix>
                <div class="input-pre">
                  <img src="../../assets/images/login_icon1.png" alt="account" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password" class="mt-30">
            <el-input
              type="password"
              show-password
              v-model="loginForm.password"
              placeholder="请输入6~12位数字和字母"
              class="item-field"
              @keyup.enter="commEvent.onLogin"
            >
              <template #prefix>
                <div class="input-pre"><img src="../../assets/images/login_icon2.png" alt="password" /></div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <div class="captcha-group">
              <el-input v-model="loginForm.code" placeholder="请输入验证码" class="captcha_cl" @keyup.enter="commEvent.onLogin">
                <template #prefix>
                  <div class="input-pre"><img src="../../assets/images/login_icon3.png" alt="password" /></div>
                </template>
              </el-input>
              <div class="captcha-code" @click="commEvent.handleInit()"><img :src="codeUrl" alt="" /></div>
            </div>
          </el-form-item>
          <el-button type="primary" color="#409cfd" class="login-button" @click="commEvent.onLogin">登&emsp;录</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue"
import { useRouter } from "vue-router"
import { HOME_URL } from "@/config"
import { loginApi, getCodeApi } from "@/api/modules/login"
import { ElNotification, FormInstance, FormRules } from "element-plus"
import { LoginReq } from "@/api/interface/login/request"
import { useUserStore } from "@/stores/modules/user"
import { useTabsStore } from "@/stores/modules/tabs"
import { useAuthStore } from "@/stores/modules/auth"
import { initDynamicRouter } from "@/routers/modules/dynamicRouter"
import { useKeepAliveStore } from "@/stores/modules/keepAlive"
import { encryptDes } from "@/utils/des"
// 参数
const router = useRouter()
const authStore = useAuthStore()
const userStore = useUserStore()
const tabsStore = useTabsStore()
const keepAliveStore = useKeepAliveStore()
const codeUrl = ref("")
const uuid = ref("")
const codeImg = ref("")
// 定义登录表单数据
const loginForm = ref({
  account: "",
  password: "",
  // account: "admin",
  // password: "Base123456!",
  code: ""
})
// 表单校验
const rules: FormRules = {
  account: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入登录密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
}
const formRef = ref<FormInstance>() // 表单实例
// 登录处理函数
const commEvent = {
  handleInit: async () => {
    try {
      const { data } = await getCodeApi() // 调用获取验证码的接口
      // 关键：拼接正确的 data URI 格式（注意是分号分隔）
      codeImg.value = `data:image/png;base64,${data.codeImg}`
      codeUrl.value = `data:image/png;base64,${data.codeImg}`
      uuid.value = data.uuid
    } catch (error) {
      console.error("获取验证码失败:", error)
    }
    console.log("codeImg", codeUrl.value)
  },
  // 登录
  onLogin: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      // 对密码进行DES加密
      const encryptedPassword = encryptDes(loginForm.value.password)
      const params: LoginReq.Login = {
        ...loginForm.value,
        password: encryptedPassword,
        uuid: uuid.value,
        codeImg: codeImg.value,
        codeEnable: true
      }
      console.log("params", params)
      const { data } = await loginApi(params)
      // 设置用户信息
      userStore.setToken(data.token)
      userStore.setUserInfo(data.sysUser)
      // 添加动态路由
      await initDynamicRouter()
      // 清空tabs、keepAlive数据
      tabsStore.setTabs([])
      keepAliveStore.setKeepAliveName([])
      // 跳转至首页
      const paths = authStore.authMenuListGet.map(item => item.path)
      if (paths.includes(HOME_URL)) {
        router.push(HOME_URL)
      } else {
        router.push(paths[0])
      }
      ElNotification({ title: "欢迎登录系统", type: "success", duration: 3000 })
    })
  }
}
onMounted(() => {
  // 自动连接
  commEvent.handleInit()
})
</script>

<style scoped lang="scss">
.mt-30 {
  margin: 30px 0 !important;
}
.mt-49 {
  margin-bottom: 30px;
}
.login-container {
  display: flex;
  width: 100%;
  height: 100vh;
  background-color: #f8f9fa;
}
.left-section {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 65%;
  h2 {
    position: absolute;
  }
  .lab-scene {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    background: #f3f0ff;
    .lab-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
      object-position: center;
      border-radius: 8px;
    }
  }
}
.platform-title {
  position: absolute;
  top: 7%;
  left: 5%;
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  line-height: 1;
  color: #240972;
}
.right-section {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 35%;
  padding: 0 114px;
  background-color: #ffffff;
  box-shadow: 0 0 10px rgb(0 0 0 / 10%);
  .form-content {
    width: 100%;
    .el-form-item--default {
      margin-bottom: 0;
    }
    .captcha-group {
      display: flex;
      gap: 10px;
      align-items: center;
      width: 100%;
      height: 100%;
      .captcha_cl {
        flex: 1;
      }
    }
    .captcha-code {
      display: flex;
      align-items: center;
      width: 80px;
      height: 50px;
      font-weight: bold;
      background: #d1d5dc;
      border-radius: 2.14px;
      img {
        width: 100%;
        height: 100%;
        border: 1px solid #d1d5dc;
      }
    }
    :deep(.el-input__prefix-inner > :last-child) {
      margin-right: 18px;
    }
    h3 {
      margin: 0;
      font-size: 22px;
      font-weight: 500;
      line-height: 1;
      color: #333333;
    }
    .line_cl {
      margin: 15px 0 40px;
      border-bottom: 1.04px solid #d4d5ff;
      .left_cl {
        width: 98px;
        border: 2px solid #9d72f7;
      }
    }
    :deep(.el-input__wrapper) {
      height: 50px;
      padding: 0 12px;
      line-height: 0;
      background-color: #f0f1fc;
      box-shadow: none;
    }
    .item-field {
      font-size: 14px;
    }
    .input-pre {
      position: relative;
      display: flex;
      align-items: center;
      width: fit-content;
      padding-right: 18px;
      font-size: 19px;
      border-right: 1px solid #cddbde;
      img {
        width: 20px;
      }
    }
    .login-button {
      width: 100%;
      height: 50px;
      padding: 0;
      margin-top: 30px;
      font-size: 20px;
      color: #ffffff;
      cursor: pointer;
      background: linear-gradient(262deg, #a074f7 0%, #6a3cf5 99%);
      border: none;
      border-radius: 6px;
      transition: background-color 0.3s;
      &:hover {
        background-color: #531d92;
      }
    }
  }
}
</style>
